import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

/**
 * 路由配置
 */
const routes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: '/dashboard',
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
            requiresAuth: false,
            title: '登录',
        },
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
            requiresAuth: true,
            title: '仪表盘',
        },
    },
    {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: {
            requiresAuth: true,
            title: '用户管理',
            permissions: ['user:read'],
        },
    },
    {
        path: '/roles',
        name: 'Roles',
        component: () => import('@/views/Roles.vue'),
        meta: {
            requiresAuth: true,
            title: '角色管理',
            permissions: ['role:read'],
        },
    },
    {
        path: '/permissions',
        name: 'Permissions',
        component: () => import('@/views/Permissions.vue'),
        meta: {
            requiresAuth: true,
            title: '权限管理',
            permissions: ['permission:read'],
        },
    },
    {
        path: '/logs',
        name: 'Logs',
        component: () => import('@/views/Logs.vue'),
        meta: {
            requiresAuth: true,
            title: '系统日志',
            permissions: ['log:read'],
        },
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue'),
        meta: {
            requiresAuth: false,
            title: '页面未找到',
        },
    },
]

/**
 * 创建路由实例
 */
const router = createRouter({
    history: createWebHistory(),
    routes,
})

/**
 * 路由守卫
 * 检查用户认证状态和权限
 */
router.beforeEach(async (to, _from, next) => {
    const authStore = useAuthStore()

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - 管理系统`
    }

    // 检查是否需要认证
    if (to.meta.requiresAuth) {
        if (!authStore.isAuthenticated) {
            // 未登录，跳转到登录页
            next({
                name: 'Login',
                query: { redirect: to.fullPath },
            })
            return
        }

        // 检查权限
        if (to.meta.permissions && Array.isArray(to.meta.permissions)) {
            const hasPermission = to.meta.permissions.some((permission) =>
                authStore.hasPermission(permission as string)
            )

            if (!hasPermission) {
                // 无权限，跳转到仪表盘
                next({ name: 'Dashboard' })
                return
            }
        }
    } else if (to.name === 'Login' && authStore.isAuthenticated) {
        // 已登录用户访问登录页，跳转到仪表盘
        next({ name: 'Dashboard' })
        return
    }

    next()
})

export default router
